import { getLimitedRoutes } from '@/utils/routerHelper'
import limitedRoutes from '@/router/limitedRoutes'
import { menuItems } from "@/router/limitedRoutes"
import { menus } from "@/router/limitedRoutes"
import { resetRouter } from '@/router'

//用户权限管理
const state = {
    user: "",
    routes: [],
    login:false,
}

const mutations = {

    SET_USER: (state, user) => {
        state.user = user
    },

    SET_ROUTES: (state, routes) => {
      
        state.routes = routes;
    },
     SET_LOGIN: (state, value) => {
      
        state.login = value;
    }
}

//调用api
const actions = {
    login({ commit }, userinfo) {

        //调用登录接口
        let { username } = userinfo;
        commit("SET_USER", username);

        let newmenus = menus
        let userRoutes = getLimitedRoutes(limitedRoutes, username);
        console.log(limitedRoutes)
        resetRouter(userRoutes)
        let test = testgetRoutes(menus, limitedRoutes)
      
        //commit("SET_ROUTES", menuItems.filter(r => r.meta.users.indexOf(username) > -1))
        commit("SET_ROUTES", test)
          commit("SET_LOGIN", true)
        return new Promise((resolve) => {
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
function testgetRoutes(menus, routes) {
    //筛选所有可用路由，并生成目录树
    //let children = []
    let result = []
    if (menus && menus.length) {
        result = routes.filter((r) => menus.some((val) => val.menukey == r.name))
        result.forEach((e) => {
            if (e.children && e.children.length > 0) {
                e.children = testgetRoutes(menus, e.children)
            }

        });
    }

    return result;

}